package config

import (
	"log"

	"github.com/casbin/casbin/v2"
	"github.com/casbin/casbin/v2/model"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var casbinEnforcer *casbin.Enforcer

// InitCasbin 初始化Casbin
func InitCasbin() error {
	// 使用SQLite作为策略存储
	db, err := gorm.Open(sqlite.Open("casbin.db"), &gorm.Config{})
	if err != nil {
		return err
	}

	// 创建适配器
	adapter, err := gormadapter.NewAdapterByDB(db)
	if err != nil {
		return err
	}

	// 定义Casbin模型
	text := `
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
`

	// 创建模型
	m, err := model.NewModelFromString(text)
	if err != nil {
		return err
	}

	// 创建执行器
	enforcer, err := casbin.NewEnforcer(m, adapter)
	if err != nil {
		return err
	}

	// 加载策略
	err = enforcer.LoadPolicy()
	if err != nil {
		return err
	}

	casbinEnforcer = enforcer
	log.Println("Casbin initialized successfully!")
	return nil
}

// GetCasbinEnforcer 获取Casbin执行器
func GetCasbinEnforcer() *casbin.Enforcer {
	return casbinEnforcer
}
